package net.pws.oos.security;

import net.pws.common.util.StringUtils;
import net.pws.common.security.SecurityContext;
import net.pws.common.security.spi.Principal;
import net.pws.common.security.spi.Role;
import net.pws.common.security.spi.resource.CachedResourceManagerFactory;
import net.pws.common.security.spi.resource.ICachedResource;
import net.pws.oos.biz.model.User;
import net.pws.oos.web.dto.UserDto;

public class SecurityUtils {
    
    public static final String RES_TASK_MAP = "/task/map";  //鸟瞰图

	public static final String RES_TASK_STATS = "/task/stats";	//具有任务管理的资源标识
	
	public static final String RES_TASK_SELF = "/task/self";   //自主任务

	/**
	 * 获得当前登录用户ID
	 * 
	 * @return
	 */
	public static String currentUserId() {
		Principal princpal = SecurityContext.getContext();
		if (princpal == null) {
			return null;
		}
		return princpal.getId();
	}

	public static UserDto currentUser() {
		Principal princpal = SecurityContext.getContext();
		if (princpal == null || princpal.getDetail() == null) {
			return null;
		}
		if (princpal.getDetail() instanceof User) {
			return (UserDto) princpal.getDetail();
		}
		return null;
	}

	public static boolean allowedUrl(String url) {
		if (StringUtils.isBlank(url)) {
			return true;
		}
		String userId = currentUserId();
		if (StringUtils.isBlank(userId)) {
			return false;
		}
		try {
			ICachedResource cachedResource = CachedResourceManagerFactory
					.getInstance().getObject().getCachedResource(userId);
			return cachedResource.allowedUrl(url);
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean allowedResource(String resourceId) {
		if (StringUtils.isBlank(resourceId)) {
			return true;
		}
		String userId = currentUserId();
		if (StringUtils.isBlank(userId)) {
			return false;
		}
		try {
			ICachedResource cachedResource = CachedResourceManagerFactory
					.getInstance().getObject().getCachedResource(userId);
			return cachedResource.allowedResource(resourceId);
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 判断当前用户拥有其中一个角色
	 * 
	 * @param codes
	 *            角色编码
	 * @return
	 */
	public static boolean hasRole(String... codes) {
		if (codes == null || codes.length == 0) {
			return true;
		}

		Principal principal = SecurityContext.getContext();
		if (principal == null) {
			return false;
		}

		Role[] roles = principal.getRoles();
		if (roles == null || roles.length == 0) {
			return false;
		}

		for (String roleCode : codes) {
			if (StringUtils.isBlank(roleCode)) {
				continue;
			}
			for (Role role : roles) {
				if (roleCode.equals(role.getCode())) {
					return true;
				}
			}
		}

		return false;
	}

	// 判断是否有管理同级及下级人员的权限
	public static boolean isManager() {
        return allowedResource(RES_TASK_STATS);
	}
}
